package com.cqjtu.store.system.service.impl;

import com.cqjtu.store.product.mapper.ProductCategoryMapper;
import com.cqjtu.store.product.mapper.ProductMapper;
import com.cqjtu.store.product.pojo.entity.Product;
import com.cqjtu.store.product.pojo.entity.ProductCategory;
import com.cqjtu.store.system.service.ProductStatsService;
import org.apache.tomcat.jni.Local;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

import static com.cqjtu.store.common.Constants.*;

/**
 * ClassName: ProductStatsService
 * Package: com.cqjtu.store.system.service.impl
 * Description:
 *
 * @Author LIEX
 * @create 2024/3/11 11:30
 * @Version 1.0
 */
@Service
public class ProductStatsServiceImpl implements ProductStatsService {
    @Resource
    StringRedisTemplate stringRedisTemplate;
    @Resource
    ProductCategoryMapper productCategoryMapper;
    @Override
    public void updateProductStats(Integer userId, Integer productId) {
        LocalDate localDate = LocalDate.now();
        ProductCategory productCategory= productCategoryMapper.getByProductId(productId);

        //当日商品浏览量KEY
        String PVKey = Product_VISITED_STATS+localDate;
        stringRedisTemplate.opsForValue().setIfAbsent(PVKey,"0",1, TimeUnit.DAYS);
        stringRedisTemplate.opsForValue().increment(PVKey);

        //当日浏览人数KEY
        String UVKey = PEOPLE_VISITED_STATS+localDate;
        stringRedisTemplate.opsForHyperLogLog().add(UVKey,userId+"");
        stringRedisTemplate.expire(UVKey,31,TimeUnit.DAYS);

        // 某商品访问量UV_KEY
        String uvProductKey = UV_PRODUCT_STATS_PREFIX+productId;
        stringRedisTemplate.opsForHyperLogLog().add(uvProductKey,userId+"");

        // 某商品访问量PV_KEY
        String pvProductKey = PV_PRODUCT_STATS_PREFIX+productId;
        stringRedisTemplate.opsForValue().setIfAbsent(pvProductKey,"0");
        stringRedisTemplate.opsForValue().increment(pvProductKey);

        //某商品分类的浏览量
        String pvProductCategoryKey =PRODUCT_CATEGORY_STATS_PREFIX+productCategory.getName();
        stringRedisTemplate.opsForValue().setIfAbsent(pvProductCategoryKey,"0");
        stringRedisTemplate.opsForValue().increment(pvProductCategoryKey);


    }

    @Override
    public void updateStats(Integer userId) {
        LocalDate localDate = LocalDate.now();
        //当日浏览人数KEY
        String UVKey = PEOPLE_VISITED_STATS+localDate;
        stringRedisTemplate.opsForHyperLogLog().add(UVKey, userId+"");
        stringRedisTemplate.expire(UVKey,31,TimeUnit.DAYS);
        System.out.println("添加成功");
    }
}
